package api

import (
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"

	"internal-net-bridge-server/internal/middleware"
	"internal-net-bridge-server/internal/models"
	"internal-net-bridge-server/internal/services"
)

// AuthHandler 认证处理器
type AuthHandler struct {
	authService   *services.AuthService
	configService *services.ConfigService
}

// NewAuthHandler 创建认证处理器实例
func NewAuthHandler(configService *services.ConfigService) *AuthHandler {
	return &AuthHandler{
		authService:   services.NewAuthService(),
		configService: configService,
	}
}

// SendVerificationCode 发送验证码
// POST /api/auth/send-code
func (h *AuthHandler) SendVerificationCode(c *gin.Context) {
	var req models.SendCodeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		models.SendBadRequest(c, "请求参数错误", err.Error())
		return
	}

	verificationID, err := h.authService.SendVerificationCode(req.PhoneNumber)
	if err != nil {
		models.SendInternalServerError(c, "发送验证码失败", err.Error())
		return
	}

	data := gin.H{
		"verification_id": verificationID,
		"expires_in":      300, // 5分钟
	}
	models.SendSuccessWithMessage(c, "验证码发送成功", data)
}

// VerifyCode 验证验证码并登录
// POST /api/auth/verify-code
func (h *AuthHandler) VerifyCode(c *gin.Context) {
	var req models.VerifyCodeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		models.SendBadRequest(c, "请求参数错误", err.Error())
		return
	}

	response, err := h.authService.VerifyCode(req.PhoneNumber, req.Code, req.VerificationID)
	if err != nil {
		models.SendInternalServerError(c, "验证失败", err.Error())
		return
	}

	if !response.Success {
		models.SendBadRequest(c, response.Message, nil)
		return
	}

	models.SendSuccessWithMessage(c, response.Message, response.Data)
}

// ValidateToken 验证token
// GET /api/auth/validate-token
func (h *AuthHandler) ValidateToken(c *gin.Context) {
	// 从Authorization header获取token
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" {
		models.SendUnauthorized(c, "缺少Authorization头")
		return
	}

	// 提取token (格式: "Bearer <token>")
	tokenParts := strings.Fields(authHeader)
	if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
		models.SendUnauthorized(c, "无效的Authorization格式")
		return
	}

	token := tokenParts[1]

	// 验证token并获取用户信息
	user, err := h.authService.ValidateToken(token)
	if err != nil {
		models.SendUnauthorized(c, "无效的token")
		return
	}

	userInfo := user.ToUserInfo()
	models.SendSuccessWithMessage(c, "token有效", userInfo)
}

// GetUserInfo 获取用户信息
// GET /api/auth/user-info
func (h *AuthHandler) GetUserInfo(c *gin.Context) {
	userID, exists := middleware.GetCurrentUserID(c)
	if !exists {
		models.SendUnauthorized(c, "未认证用户")
		return
	}

	userInfo, err := h.authService.GetUserInfo(userID)
	if err != nil {
		models.SendInternalServerError(c, "获取用户信息失败", err.Error())
		return
	}

	models.SendSuccess(c, userInfo)
}

// Logout 登出
// POST /api/auth/logout
func (h *AuthHandler) Logout(c *gin.Context) {
	token, exists := middleware.GetCurrentToken(c)
	if !exists {
		models.SendUnauthorized(c, "未认证用户")
		return
	}

	err := h.authService.Logout(token)
	if err != nil {
		models.SendInternalServerError(c, "登出失败", err.Error())
		return
	}

	models.SendSuccessWithMessage(c, "登出成功", nil)
}

// GetAppConfig 获取应用配置
// GET /app/config
func (h *AuthHandler) GetAppConfig(c *gin.Context) {
	// 返回应用配置信息
	config := gin.H{
		"app_name":    "Internal Net Bridge",
		"version":     "1.0.0",
		"api_version": "v1",
		"features": gin.H{
			"sms_login":      true,
			"auto_register":  true,
			"tunnel_service": true,
		},
		"limits": gin.H{
			"max_tunnels_per_user":   10,
			"max_request_per_minute": 60,
		},
		"settings": gin.H{
			"verification_code_expires": 300,    // 5分钟
			"token_expires":             604800, // 7天
		},
	}

	models.SendSuccess(c, config)
}

// RefreshToken 刷新token
// POST /api/auth/refresh-token
func (h *AuthHandler) RefreshToken(c *gin.Context) {
	token, exists := middleware.GetCurrentToken(c)
	if !exists {
		models.SendUnauthorized(c, "未认证用户")
		return
	}

	// 这里可以实现token刷新逻辑
	// 目前先返回当前token
	data := gin.H{
		"token":      token,
		"expires_in": 604800, // 7天
	}
	models.SendSuccessWithMessage(c, "token刷新成功", data)
}

// GetUserList 获取用户列表 (管理员接口)
// GET /api/auth/users
func (h *AuthHandler) GetUserList(c *gin.Context) {
	// 分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}

	// 获取总数和分页数据需要通过服务层实现
	// 这里先返回一个示例响应
	userList := []models.UserInfo{}
	total := int64(0)

	models.SendPaginationSuccess(c, userList, total, page, pageSize)
}

// GetClientConfig 获取客户端配置
// GET /api/client/config
func (h *AuthHandler) GetClientConfig(c *gin.Context) {
	appConfig, err := h.configService.GetAppConfig()
	if err != nil {
		models.SendInternalServerError(c, "获取配置失败", err.Error())
		return
	}

	// 返回客户端配置
	clientConfig := gin.H{
		"base_url":        appConfig.Client.BaseURL,
		"tcp_tunnel_host": appConfig.Client.TCPTunnelHost,
		"tcp_tunnel_port": appConfig.Client.TCPTunnelPort,
		"timeout_seconds": appConfig.Client.TimeoutSeconds,
		"mock_delay_ms":   appConfig.Client.MockDelayMs,
		"default_domain":  appConfig.Client.DefaultDomain,
		"auto_reconnect":  appConfig.Client.AutoReconnect,
	}

	models.SendSuccess(c, clientConfig)
}
